import tkinter as tk
from tkinter import filedialog
import sys

def openDesttopDirOrFile(param):
    print("进入文件夹或文件打开过程..")
    print("参数情况：")
    print(param)

    # 参数处理
    task_id = param.get('task_id') if param.get('task_id') is not None else get_current_timestamp()                     # TaskId默认为当前时间

    # 打开文件参数
    open_type = int(param.get('open_type')) if param.get('open_type') is not None else 0                                # 打开文件类型：0:文件；1：文件夹

    # open_type = 2 用于开发测试
    if open_type == 2:
        path = "C:/testpath/test.file"
        print('测试数据返回，路径为：',path)
        return {"code": 0, "msg": "[测试]获取本地路径成功", "data": path}

    return openDirOrFile(open_type)


def openDirOrFile(open_type):
    try:
        root = tk.Tk()
        root.withdraw()
        # 实现root窗口的置顶显示
        root.wm_attributes('-topmost',1)
        # root.mainloop()
        if open_type == 1:
            print('选择文件夹：')
            path = filedialog.askdirectory()
            print('文件夹选择完毕，路径为：',path)
        else:
            print('选择文件：')
            path = filedialog.askopenfilename()
            print('文件选择完毕，路径为：',path)

        # 关闭Tkinter窗口（以下两个命令都可以）
        root.destroy()
        # root.quit

        return {"code": 0, "msg": "获取本地路径成功", "data": path}
    except Exception as e:
        print("打开文件夹或文件失败: %s" % e)
        return {"code": -1, "msg": "打开文件夹或文件失败！"}


def redirect_stdout_to_tkinter(text_widget):
    class StdoutRedirector:
        def __init__(self, text_widget):
            self.text_widget = text_widget

        def write(self, message):
            self.text_widget.insert('end', message)
            self.text_widget.see('end')

    sys.stdout = StdoutRedirector(text_widget)


# 设置弹窗大小
# 参考：https://blog.csdn.net/lizhiwei309/article/details/126877672
def show_msg_to_tkinter(msg):
    # 创建Tkinter窗口
    window = tk.Tk()
    # window.geometry("768x300")
    #黑色背景
    # window.config(bg='black')

    #设置窗口大小，并将窗口放置在屏幕中央
    width = 800
    height = 400
    g_screenwidth = window.winfo_screenwidth()
    g_screenheight = window.winfo_screenheight()
    alignstr = '%dx%d+%d+%d' % (width, height, (g_screenwidth-width)/2, (g_screenheight-height)/2)
    window.geometry(alignstr)

    # 创建文本框用于显示输出
    output_text = tk.Text(window)
    # output_text = tk.Text(window, width=100, heigh=40)
    # output_text.pack()
    output_text.pack(fill="both", expand="yes")

    # 重定向标准输出到文本框
    redirect_stdout_to_tkinter(output_text)

    window.attributes('-topmost', True)
    # 执行print语句，输出将显示在文本框中
    print(msg)

    # 运行Tkinter主循环
    window.mainloop()


if __name__ == '__main__':
    show_msg_to_tkinter("test123")